# test01_subprocess.py
## 练习 1：调用 ping 命令   ping www.baidu.com
# **需求**
# - **调用 ping 命令**  subprocess.run(要执行的指令, shell=True)
#   - 编写 **ping 函数**   def ping(host):
#   - 用于测试远程主机的联通性 ping -c 2 host &> /dev/null
#   - ping 通显示：**x.x.x.x:up** returncode:0
#   - ping 不通显示：**x.x.x.x:down** returncode != 0
# subprocess: 通过python去执行shell指令的模块
import subprocess
def ping(host):  # host: ping的主机地址, 是字符串类型
    jg = subprocess.run(
        "ping -c 2 " + host + " &> /dev/null", shell=True
        # ping -c 2空格127.0.0.1空格&> /dev/null
    )
    # returncode为0，表示subprocess.run中执行的指令成功
    # 判断执行的结果是成功还是失败
    if jg.returncode == 0: # if 成功:
        print(host + ":up")
    else:
        print(host + ":down")
ping("127.0.0.1")  # host = "127.0.0.1"